package org.meow.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.meow.dto.NewsDTO;
import org.meow.entity.News;
import org.meow.mapper.NewsMapper;
import org.meow.service.NewsService;
import org.meow.utils.MeowStr;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * &#064;Date: 24/04/22-19:08
 * &#064;Description:
 */
@Service
public class NewsServiceImpl implements NewsService {

  @Autowired
  private NewsMapper newsMapper;

  @Override
  public List<News> getNewsList() {
    return newsMapper.selectList(null);
  }

  @Override
  public News getNewsById(Integer id) {
    return newsMapper.selectById(id);
  }

  @Override
  public void save(NewsDTO newsDTO) {
    News news = new News();
    BeanUtils.copyProperties(newsDTO, news);
    news.setPublishDateTime(LocalDateTime.now());
    news.setUpdateDateTime(LocalDateTime.now());
    newsMapper.insert(news);
  }

  @Override
  public boolean updateNews(Integer id, NewsDTO news) {
    LambdaUpdateWrapper<News> updateWrapper = new LambdaUpdateWrapper<>();
    updateWrapper
        .eq(News::getId, id)
        .set(MeowStr.isStrNotBlank(news.getTitle()), News::getTitle, news.getTitle())
        .set(MeowStr.isStrNotBlank(news.getContent()), News::getContent, news.getContent())
        .set(News::getUpdateDateTime, LocalDateTime.now());
    return newsMapper.update(null, updateWrapper) != 0;
  }

  @Override
  public boolean deleteNews(Integer id) {
    return newsMapper.deleteById(id) != 0;
  }
}
